

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Cai Shibo">
  <meta name="keywords" content="cc">
  
    <meta name="description" content="该文章记录对 回溯 相关题目的分析理解。">
<meta property="og:type" content="article">
<meta property="og:title" content="算法---回溯">
<meta property="og:url" content="https://hahsx_xd.gitee.io/2022/03/24/%E7%AE%97%E6%B3%95--%E5%9B%9E%E6%BA%AF/index.html">
<meta property="og:site_name" content="🍊CAI SHIBO🥬">
<meta property="og:description" content="该文章记录对 回溯 相关题目的分析理解。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-03-24T12:25:00.000Z">
<meta property="article:modified_time" content="2022-11-29T07:14:46.511Z">
<meta property="article:author" content="Cai Shibo">
<meta property="article:tag" content="回溯">
<meta name="twitter:card" content="summary_large_image">
  
  
  <title>算法---回溯 - 🍊CAI SHIBO🥬</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"hahsx_xd.gitee.io","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":".|","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":"#"},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":5},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":true,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="🍊CAI SHIBO🥬" type="application/atom+xml">
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>^_^ 🥬 CC</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="算法---回溯">
              
            </span>

            
              <div class="mt-3">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-author" aria-hidden="true"></i>
      Cai Shibo
    </span>
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-03-24 20:25" pubdate>
        2022年3月24日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      5.4k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      28 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">算法---回溯</h1>
            
              <p class="note note-info">
                
                  最后更新：23 天前
                
              </p>
            
            <div class="markdown-body">
              <p><strong>该文章记录对 回溯 相关题目的分析理解。</strong></p>
<span id="more"></span>

<hr>
<h4 id="JZ12-矩阵中的路径-M"><a href="#JZ12-矩阵中的路径-M" class="headerlink" title="JZ12 矩阵中的路径 M"></a>JZ12 矩阵中的路径 M</h4><p>描述：请设计一个函数，用来判断在一个n乘m的矩阵中是否存在一条包含某长度为len的字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始，每一步可以在矩阵中向左，向右，向上，向下移动一个格子。如果一条路径经过了矩阵中的某一个格子，则该路径不能再进入该格子。</p>
<p>解：遍历矩阵的每个元素，检查以其为开始能否组成目标字符串。<br><strong>dfs思想：</strong>以每个元素开始后，都需要检查其向左向右向上向下的情况，因此使用递归算法。<br>每次都需要先检查其是否已经组成目标字符串（即匹配的字符长度是否等于目标字符串长度）；再检查下标是否越界（即走一步后有没有走出矩阵）；然后判断当前字符是否与目标字符相同，相同则可以继续走下一步。<br><strong>注意：每次走之前要先记录当前的字符，然后将其变改变（用于表示该字符无法再次到达），如果当前路径最后走不通，需要恢复矩阵。</strong></p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.util.*;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">hasPath</span> <span class="hljs-params">(<span class="hljs-keyword">char</span>[][] matrix, String word)</span> </span>&#123;<br>        <span class="hljs-comment">// write code here</span><br>        <span class="hljs-keyword">int</span> n = matrix.length, m = matrix[<span class="hljs-number">0</span>].length;<br>        <span class="hljs-keyword">char</span>[] chs = word.toCharArray();<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; n; ++i) &#123;<br>            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; m; ++j) &#123;<br>                <span class="hljs-keyword">if</span> (dfs(matrix, chs, <span class="hljs-number">0</span>, i, j)) &#123;<br>                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;<br>                &#125;<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">dfs</span><span class="hljs-params">(<span class="hljs-keyword">char</span>[][] matrix, <span class="hljs-keyword">char</span>[] cur, <span class="hljs-keyword">int</span> count, <span class="hljs-keyword">int</span> i, <span class="hljs-keyword">int</span> j)</span> </span>&#123;<br>        <span class="hljs-keyword">if</span> (count == cur.length) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;<br>        &#125;<br>        <span class="hljs-keyword">if</span> (i &lt; <span class="hljs-number">0</span> || i &gt;= matrix.length || j &lt; <span class="hljs-number">0</span> || j &gt;= matrix[<span class="hljs-number">0</span>].length) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;<br>        &#125;<br>        <span class="hljs-keyword">char</span> temp;<br>        <span class="hljs-keyword">if</span> (matrix[i][j] == cur[count]) &#123;<br>            count ++;<br>            <span class="hljs-comment">//记录当前的i，j下的char，之后回溯可以恢复matrix</span><br>            temp = matrix[i][j];<br>            <span class="hljs-comment">//改变matrix[i][j]的值，表示其已经被使用过</span><br>            matrix[i][j] = <span class="hljs-string">&#x27;.&#x27;</span>;<br>            <span class="hljs-keyword">boolean</span> res = dfs(matrix, cur, count, i - <span class="hljs-number">1</span>, j) || dfs(matrix, cur, count, i + <span class="hljs-number">1</span>, j) <br>                || dfs(matrix, cur, count, i, j - <span class="hljs-number">1</span>) || dfs(matrix, cur, count, i, j + <span class="hljs-number">1</span>);<br>            <span class="hljs-comment">//当前开始的路径不通，回溯恢复matrix</span><br>            matrix[i][j] = temp;<br>            <span class="hljs-keyword">return</span> res;<br>        &#125;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<h4 id="LC17-电话号码的字母组合-M"><a href="#LC17-电话号码的字母组合-M" class="headerlink" title="LC17 电话号码的字母组合 M"></a>LC17 电话号码的字母组合 M</h4><p>描述：给定一个仅包含数字 2-9 的字符串，返回所有它能表示的字母组合。答案可以按 任意顺序 返回。<br>给出数字到字母的映射如下（与电话按键相同）。注意 1 不对应任何字母。</p>
<p>解：</p>
<ol>
<li><strong>回溯法</strong>：dfs思想，每一个都先到最后，返回结果后回溯。 <figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br><br>    <span class="hljs-keyword">public</span> List&lt;String&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>    <span class="hljs-keyword">public</span> String[] map = <span class="hljs-keyword">new</span> String[]&#123;<span class="hljs-string">&quot;abc&quot;</span>, <span class="hljs-string">&quot;def&quot;</span>, <span class="hljs-string">&quot;ghi&quot;</span>, <span class="hljs-string">&quot;jkl&quot;</span>, <span class="hljs-string">&quot;mno&quot;</span>, <span class="hljs-string">&quot;pqrs&quot;</span>, <span class="hljs-string">&quot;tuv&quot;</span>, <span class="hljs-string">&quot;wxyz&quot;</span>&#125;;<br>    <span class="hljs-keyword">public</span> StringBuilder sb = <span class="hljs-keyword">new</span> StringBuilder();<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;String&gt; <span class="hljs-title">letterCombinations</span><span class="hljs-params">(String digits)</span> </span>&#123;<br>        <span class="hljs-keyword">if</span> (digits == <span class="hljs-keyword">null</span> || digits.length() == <span class="hljs-number">0</span>) &#123;<br>            <span class="hljs-keyword">return</span> list;<br>        &#125;<br>        backtrack(digits, <span class="hljs-number">0</span>);<br>        <span class="hljs-keyword">return</span> list;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">backtrack</span><span class="hljs-params">(String digits, <span class="hljs-keyword">int</span> index)</span> </span>&#123;<br>        <span class="hljs-keyword">if</span> (index == digits.length()) &#123;<br>            list.add(sb.toString());<br>            <span class="hljs-keyword">return</span>;<br>        &#125;<br>        <span class="hljs-keyword">char</span>[] chs = map[digits.charAt(index) - <span class="hljs-string">&#x27;2&#x27;</span>].toCharArray();<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span> c : chs) &#123;<br>            sb.append(c);<br>            backtrack(digits, index + <span class="hljs-number">1</span>);<br>            sb.deleteCharAt(sb.length() - <span class="hljs-number">1</span>);<br>        &#125;<br>    &#125;<br><br>&#125;<br></code></pre></div></td></tr></table></figure>
</li>
<li><strong>队列</strong>：bfs思想。<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br><br>    <span class="hljs-keyword">public</span> List&lt;String&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>    <span class="hljs-keyword">public</span> String[] map = <span class="hljs-keyword">new</span> String[]&#123;<span class="hljs-string">&quot;abc&quot;</span>, <span class="hljs-string">&quot;def&quot;</span>, <span class="hljs-string">&quot;ghi&quot;</span>, <span class="hljs-string">&quot;jkl&quot;</span>, <span class="hljs-string">&quot;mno&quot;</span>, <span class="hljs-string">&quot;pqrs&quot;</span>, <span class="hljs-string">&quot;tuv&quot;</span>, <span class="hljs-string">&quot;wxyz&quot;</span>&#125;;<br>    <span class="hljs-keyword">public</span> StringBuilder sb = <span class="hljs-keyword">new</span> StringBuilder();<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;String&gt; <span class="hljs-title">letterCombinations</span><span class="hljs-params">(String digits)</span> </span>&#123;<br>        <span class="hljs-keyword">if</span> (digits == <span class="hljs-keyword">null</span> || digits.length() == <span class="hljs-number">0</span>) &#123;<br>            <span class="hljs-keyword">return</span> list;<br>        &#125;<br><br>        <span class="hljs-keyword">char</span>[] chs = digits.toCharArray();<br>        Queue&lt;StringBuilder&gt; q = <span class="hljs-keyword">new</span> LinkedList&lt;&gt;();<br><br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span> c : chs) &#123;<br>            <span class="hljs-keyword">int</span> index = c - <span class="hljs-string">&#x27;2&#x27;</span>;<br>            <span class="hljs-keyword">int</span> n = q.size();<br>            <span class="hljs-keyword">if</span> (n == <span class="hljs-number">0</span>) &#123;<br>                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span> h : map[index].toCharArray()) &#123;<br>                    q.offer(<span class="hljs-keyword">new</span> StringBuilder(String.valueOf(h)));<br>                &#125;<br>            &#125;<br>            <span class="hljs-keyword">else</span> &#123;<br>                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; n; ++i) &#123;<br>                    sb = q.poll();<br>                    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span> h : map[index].toCharArray()) &#123;<br>                        StringBuilder temp = <span class="hljs-keyword">new</span> StringBuilder(sb);<br>                        q.offer(temp.append(h));<br>                    &#125;<br>                &#125;<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">while</span> (q.size() &gt; <span class="hljs-number">0</span>) &#123;<br>            list.add(q.poll().toString());<br>        &#125;<br>        <span class="hljs-keyword">return</span> list;<br>    &#125;<br><br>&#125;<br></code></pre></div></td></tr></table></figure></li>
</ol>
<hr>
<h4 id="LC417-太平洋大西洋水流问题-M"><a href="#LC417-太平洋大西洋水流问题-M" class="headerlink" title="LC417 太平洋大西洋水流问题 M"></a>LC417 太平洋大西洋水流问题 M</h4><p>描述：<br>有一个 m × n 的矩形岛屿，与 太平洋 和 大西洋 相邻。 “太平洋” 处于大陆的左边界和上边界，而 “大西洋” 处于大陆的右边界和下边界。<br>这个岛被分割成一个由若干方形单元格组成的网格。给定一个 m x n 的整数矩阵 heights ， heights[r][c] 表示坐标 (r, c) 上单元格 高于海平面的高度 。<br>岛上雨水较多，如果相邻单元格的高度 小于或等于 当前单元格的高度，雨水可以直接向北、南、东、西流向相邻单元格。水可以从海洋附近的任何单元格流入海洋。<br>返回 网格坐标 result 的 2D列表 ，其中 result[i] = [ri, ci] 表示雨水可以从单元格 (ri, ci) 流向 <strong>太平洋和大西洋</strong> 。</p>
<p>解：要找出太平洋和大西洋均可到达的单元格。遍历每个单元格（dfs、bfd）判断其是否可同时到达 <strong>左或上、右或下</strong> 边界。</p>
<p>优化：遍历所有单元格，有较多重复计算。<strong>反向判断 左、上 与 右、下单元格分别能由哪些单元格到达，重复的单元格即为目标单元格</strong>。</p>
<ol>
<li>dfs算法<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br><br>    <span class="hljs-keyword">public</span> List&lt;List&lt;Integer&gt;&gt; pacificAtlantic(<span class="hljs-keyword">int</span>[][] heights) &#123;<br>        <span class="hljs-keyword">int</span> m = heights.length;<br>        <span class="hljs-keyword">int</span> n = heights[<span class="hljs-number">0</span>].length;<br>        List&lt;List&lt;Integer&gt;&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        <span class="hljs-keyword">if</span> (m == <span class="hljs-number">1</span> || n == <span class="hljs-number">1</span>) &#123;<br>            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; m; ++i) &#123;<br>                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; n; ++j) &#123;<br>                    List&lt;Integer&gt; temp = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;(<span class="hljs-number">2</span>);<br>                    temp.add(i);<br>                    temp.add(j);<br>                    list.add(temp);<br>                &#125;<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">else</span> &#123;<br>            <span class="hljs-keyword">boolean</span> dp[][] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">boolean</span>[m][n];<br>            <span class="hljs-keyword">boolean</span> rdp[][] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">boolean</span>[m][n];<br>            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; m; ++i) &#123;<br>                <span class="hljs-keyword">if</span> (i == <span class="hljs-number">0</span>) &#123;<br>                    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; n; ++j) &#123;<br>                        dp[i][j] = <span class="hljs-keyword">true</span>;<br>                        dfs(i, j, heights, dp);<br>                    &#125;<br>                &#125;<br>                <span class="hljs-keyword">else</span> &#123;<br>                    dp[i][<span class="hljs-number">0</span>] = <span class="hljs-keyword">true</span>;<br>                    dfs(i, <span class="hljs-number">0</span>, heights, dp);<br>                &#125;<br>            &#125;<br>            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; m; ++i) &#123;<br>                <span class="hljs-keyword">if</span> (i == m - <span class="hljs-number">1</span>) &#123;<br>                    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; n; ++j) &#123;<br>                        rdp[i][j] = <span class="hljs-keyword">true</span>;<br>                        dfs(i, j, heights, rdp);<br>                    &#125;<br>                &#125;<br>                <span class="hljs-keyword">else</span> &#123;<br>                    rdp[i][n - <span class="hljs-number">1</span>] = <span class="hljs-keyword">true</span>;<br>                    dfs(i, n - <span class="hljs-number">1</span>, heights, rdp);<br>                &#125;<br>            &#125;<br>            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; m; ++i) &#123;<br>                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; n; ++j) &#123;<br>                    <span class="hljs-keyword">if</span> (dp[i][j] &amp;&amp; rdp[i][j]) &#123;<br>                        List&lt;Integer&gt; temp = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>                        temp.add(i);<br>                        temp.add(j);<br>                        list.add(temp);<br>                    &#125;<br>                &#125;<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">return</span> list;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">dfs</span><span class="hljs-params">(<span class="hljs-keyword">int</span> x, <span class="hljs-keyword">int</span> y, <span class="hljs-keyword">int</span>[][] heights, <span class="hljs-keyword">boolean</span>[][] dp)</span> </span>&#123;<br>        <span class="hljs-keyword">if</span> (x + <span class="hljs-number">1</span> &lt; heights.length &amp;&amp; !dp[x + <span class="hljs-number">1</span>][y] &amp;&amp; heights[x][y] &lt;= heights[x+<span class="hljs-number">1</span>][y]) &#123;<br>            dp[x + <span class="hljs-number">1</span>][y] = <span class="hljs-keyword">true</span>;<br>            dfs(x + <span class="hljs-number">1</span>, y, heights, dp);<br>        &#125;<br>        <span class="hljs-keyword">if</span> (x - <span class="hljs-number">1</span> &gt;= <span class="hljs-number">0</span> &amp;&amp; !dp[x - <span class="hljs-number">1</span>][y] &amp;&amp; heights[x][y] &lt;= heights[x-<span class="hljs-number">1</span>][y]) &#123;<br>            dp[x - <span class="hljs-number">1</span>][y] = <span class="hljs-keyword">true</span>;<br>            dfs(x - <span class="hljs-number">1</span>, y, heights, dp);<br>        &#125;<br>        <span class="hljs-keyword">if</span> (y + <span class="hljs-number">1</span> &lt; heights[<span class="hljs-number">0</span>].length &amp;&amp; !dp[x][y + <span class="hljs-number">1</span>] &amp;&amp; heights[x][y] &lt;= heights[x][y+<span class="hljs-number">1</span>]) &#123;<br>            dp[x][y + <span class="hljs-number">1</span>] = <span class="hljs-keyword">true</span>;<br>            dfs(x, y + <span class="hljs-number">1</span>, heights, dp);<br>        &#125;<br>        <span class="hljs-keyword">if</span> (y - <span class="hljs-number">1</span> &gt;= <span class="hljs-number">0</span> &amp;&amp; !dp[x][y - <span class="hljs-number">1</span>] &amp;&amp; heights[x][y] &lt;= heights[x][y-<span class="hljs-number">1</span>]) &#123;<br>            dp[x][y - <span class="hljs-number">1</span>] = <span class="hljs-keyword">true</span>;<br>            dfs(x, y - <span class="hljs-number">1</span>, heights, dp);<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure></li>
</ol>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E7%AE%97%E6%B3%95/">算法</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E5%9B%9E%E6%BA%AF/">回溯</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章未经允许，严禁转载！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/03/24/%E7%AE%97%E6%B3%95--%E6%8E%92%E5%BA%8F/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">算法---排序</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/03/21/%E7%AE%97%E6%B3%95-%E5%85%B6%E4%BB%96%E7%AE%97%E6%B3%95/">
                        <span class="hidden-mobile">算法 --- 其他算法</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     CC <i class="iconfont icon-love"></i> XX
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    
      <script  src="/js/img-lazyload.js" ></script>
    
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
